package com.example.weblending.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.weblending.domain.ApplyUnset;
import com.example.weblending.domain.User;
import com.example.weblending.exception.GlobalException;
import com.example.weblending.service.ApplyUnsetService;
import com.example.weblending.service.UserService;
import com.example.weblending.mapper.UserMapper;
import com.example.weblending.utils.JwtUtils;
import com.example.weblending.utils.MD5;
import com.example.weblending.utils.MailUtil;
import com.example.weblending.vo.PasswordVo;
import com.example.weblending.vo.UnsetPassword;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService{
    @Resource
    private ApplyUnsetService applyUnsetService;
    @Resource
    private UserService userService;
    @Resource
    private VerifyMapper verifyMapper;

    @Resource
    private MailUtil mailUtil;
    @Override
    public String login(User member) {
        //获取登录名称密码
        String name=member.getName();
        String password=member.getPassword();
        //手机号密码非空判断
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new GlobalException(20001,"登录失败");
        }
        //判断手机号是否正确
        QueryWrapper<User>wrapper=new QueryWrapper<>();
        wrapper.eq("name",name);
        User one=baseMapper.selectOne(wrapper);
        if (one == null){
            throw new GlobalException(20001,"登录失败");
        }
        //判断密码
        //把输入的密码加密再与数据库比较
        System.out.println(MD5.encrypt(password));
        if (!MD5.encrypt(password).equals(one.getPassword())){
            throw new GlobalException(20001,"登录失败");
        }
        //判断用户是否禁用
        //if (one.getIsDisabled()){
        //   throw new GlobalException(20001,"登录失败");
        //}
        //登录成功
        //生产token
        if(one.getUnset()!=null&&one.getUnset()==1){
            applyUnsetService.disable(one.getUid());
            one.setUnset(0);
            userService.updateById(one);
        }
        member.setPermission(one.getPermission());
        member.setStatus(one.getStatus());
        return JwtUtils.getJwtToken(one.getUid(),one.getPermission());
    }

    @Override
    public boolean updatePassword(PasswordVo passwordVo,int id) {
        //手机号密码非空判断
        if (StringUtils.isEmpty(passwordVo.getPassword()) || StringUtils.isEmpty(passwordVo.getNewPassword())){
            throw new GlobalException(20001,"登录失败");
        }
        User u=this.getById(id);
        if (u == null){
            throw new GlobalException(20001,"登录失败");
        }
        if (!MD5.encrypt(passwordVo.getPassword()).equals(u.getPassword())){
            throw new GlobalException(20001,"密码校验失败");
        }
        u.setPassword(MD5.encrypt(passwordVo.getNewPassword()));
        return this.updateById(u);
    }

    @Override
    public boolean setStaus(String uid,String id ,int status) {
        User user=this.getById(id);
        if(user==null){
            throw new GlobalException(20001,"登录失败");
        }
        if(user.getPermission()==0){
            throw new GlobalException(20001,"您无权操作");
        }
        user= this.getById(uid);
        user.setStatus(status);
        return this.updateById(user);
    }


    @Override
    public boolean register(User user, boolean admin) {
        if(this.isUserNameExist(user.getName())){
            throw new GlobalException(30001,"该登录名已经存在");
        }
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        if(admin){
            user.setPassword(uuid);
        }
        user.setPassword(MD5.encrypt(user.getPassword()));
        if(user.getPermission()==0){
            user.setCleannum(0);
            user.setAnalyzenum(0);
        }else{
            user.setCleannum(-1);
            user.setAnalyzenum(-1);
        }
        boolean success=this.save(user);
        user.setPassword(uuid);
        user.setStatus(null);
        user.setPermission(null);
        user.setCleannum(null);
        user.setAnalyzenum(null);
        user.setStatus(null);
        return  success;
    }

    @Override
    public Page<User> getListyId(long page, long limit, User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if(user.getPermission()==0){
            throw  new GlobalException(403,"您无权操作");
        }
        wrapper.eq("permission",user.getPermission()-1);
        Page<User> pageParam = new Page<>(page,limit);
        baseMapper.selectPage(pageParam,wrapper);
        pageParam.getRecords();
        List<User> list=pageParam.getRecords();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setPassword(null);
        }
        //map返回
        return pageParam;
    }

    /**
     * 根据用户名寻找用户
     * @param name 用户名
     * @return
     */
    @Override
    public User findOneByName(String name) {
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("name",name);
        return getOne(userQueryWrapper);
    }

    @Override
    public String resetLogin(UnsetPassword apply) {
        if(apply.getOneCode()==null||"".equals(apply.getOneCode())){
            throw new GlobalException(403,"请联系管理员获得一次性登录码");
        }
        User user=userService.findOneByName(apply.getName());
        if (user==null){
            throw new GlobalException(404,"该用户未找到");
        }
        QueryWrapper<ApplyUnset> wrapper=new QueryWrapper<>();

        wrapper.eq("uid",user.getUid());
        wrapper.eq("certificate",apply.getCertificate());
        wrapper.eq("code",apply.getOneCode());
        ApplyUnset applyUnset=applyUnsetService.getOne(wrapper);
        if(applyUnset==null){
            throw new GlobalException(404,"未找到该申请，请检查用户名，凭证，一次性登录码是否一致");
        }
        System.out.println(applyUnset);
        if(applyUnset.getState()!=1){
            throw new GlobalException(403,"该一次性登录码无效");
        }
        applyUnset.setState(2);
        applyUnsetService.updateById(applyUnset);
        return JwtUtils.getJwtToken( user.getUid(),user.getPermission());
    }

    @Override
    public boolean verifyMail(String id, String salt) {
        User user =this.getById(id);
        if (user.getStatus()!=2){
           return false;
        }
        Verify verify=verifyMapper.selectById(id);
        if (verify==null){
            return false;
        }
        if (!salt.equals(verify.getSalt())||verify.getState()!=0){
            return false;
        }
        verify.setVerifyTime(new Timestamp(System.currentTimeMillis()));
        verify.setState(1);
        verifyMapper.updateById(verify);
        user.setStatus(0);
        this.updateById(user);
        return true;
    }

    @Override
    public boolean verifyToMail(User user) {
        if (StringUtils.isEmpty(user.getEmail())){
            throw new GlobalException(403,"您没有设置邮箱，请先更新个人信息");
        }
        Verify verify=new Verify();
        verify.setId(user.getUid());
        verify.setState(0);
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        verify.setSalt(uuid);
        verifyMapper.insert(verify);
        mailUtil.getVerify(uuid, user.getName(), String.valueOf(user.getUid()),user.getEmail());
        return true;
    }


    /**
     * 根据用户名判断该用户存不存在
     * @param name 用户名
     * @return
     */
    public boolean isUserNameExist(String name){
       User user=this.findOneByName(name);
       return user!=null;
    }
}




